<template>
  <div class="personal-center-page">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2 class="page-title gradient-text">个人中心</h2>
      <p class="page-subtitle">管理您的个人信息和会员权益</p>
    </div>

    <div class="content-grid">
      <!-- 左侧：用户信息 -->
      <div class="user-info-section glass">
        <div class="section-header">
          <h3 class="section-title">
            <UserOutlined class="section-icon" />
            个人信息
          </h3>
          <a-button 
            type="link" 
            @click="showEditModal = true"
            :icon="h(EditOutlined)"
          >
            编辑
          </a-button>
        </div>

        <div class="user-profile-main">
          <!-- 头像区域 -->
          <div class="avatar-section">
            <div class="avatar-container" :class="getVipAvatarClass()">
              <a-avatar 
                :size="100" 
                :src="userInfo?.userAvatar" 
                class="user-avatar"
              >
                {{ userInfo?.userName?.charAt(0) }}
              </a-avatar>
              <!-- VIP标识 -->
              <div v-if="userInfo?.vipLevel && userInfo.vipLevel > 0" class="vip-badge">
                <div :class="getVipBadgeClass()">
                  {{ userInfo.vipLevel === 1 ? 'VIP' : 'SVIP' }}
                </div>
              </div>
              <!-- 更换头像按钮 -->
              <a-button 
                type="text"
                size="small" 
                @click="showAvatarModal = true"
                class="change-avatar-overlay"
                :icon="h(EditOutlined)"
              >
                更换
              </a-button>
            </div>
          </div>

          <!-- 用户信息展示 -->
          <div class="user-details">
            <div class="info-item">
              <span class="info-label">用户ID：</span>
              <span class="info-value">{{ userInfo?.id }}</span>
            </div>
            
            <div class="info-item">
              <span class="info-label">用户账号：</span>
              <span class="info-value">{{ userInfo?.userAccount }}</span>
            </div>
            
            <div class="info-item">
              <span class="info-label">用户名：</span>
              <span class="info-value">{{ userInfo?.userName }}</span>
            </div>
            
            <div class="info-item">
              <span class="info-label">角色：</span>
              <a-tag :color="userInfo?.userRole === 'admin' ? 'red' : 'blue'">
                {{ userInfo?.userRole === 'admin' ? '管理员' : '普通用户' }}
              </a-tag>
            </div>
            
            <div class="info-item">
              <span class="info-label">会员等级：</span>
              <a-tag 
                v-if="userInfo?.vipLevel && userInfo.vipLevel > 0"
                :color="userInfo.vipLevel === 1 ? 'gold' : 'purple'"
              >
                {{ userInfo.vipLevel === 1 ? 'VIP会员' : 'SVIP会员' }}
              </a-tag>
              <span v-else class="info-value">普通用户</span>
            </div>
            
            <div class="info-item">
              <span class="info-label">注册时间：</span>
              <span class="info-value">{{ formatDate(userInfo?.createTime) }}</span>
            </div>
            
            <div v-if="userInfo?.vipLevel && userInfo.vipLevel > 0" class="info-item">
              <span class="info-label">会员到期：</span>
              <span 
                class="info-value"
                :class="{ 'expire-warning': isVipExpiringSoon() }"
              >
                {{ isVipForever() ? '永久有效' : formatDate(userInfo?.expireTime) }}
              </span>
            </div>
            
            <div class="info-item profile-item">
              <span class="info-label">个人简介：</span>
              <div class="profile-content">
                <p v-if="userInfo?.userProfile" class="profile-text">
                  {{ userInfo.userProfile }}
                </p>
                <span v-else class="info-value empty">暂无个人简介</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 空间使用情况 -->
        <div v-if="spaceUsage.length > 0" class="space-usage-section">
          <h4 class="usage-title">
            <DatabaseOutlined class="section-icon" />
            空间使用情况
          </h4>
          <div class="space-cards">
            <div 
              v-for="space in spaceUsage" 
              :key="space.id" 
              class="space-card"
            >
              <div class="space-card-header">
                <div class="space-info">
                  <span class="space-name">{{ space.name }}</span>
                  <span class="space-type">{{ getSpaceTypeName(space.type) }}</span>
                </div>
                <span v-if="space.pictureCount !== undefined" class="picture-count">
                  {{ space.pictureCount }} 张图片
                </span>
              </div>
              
              <div class="space-stats">
                <div class="stat-item">
                  <span class="stat-label">已用空间</span>
                  <span class="stat-value">{{ formatSize(space.used) }}</span>
                </div>
                <div class="stat-item">
                  <span class="stat-label">总容量</span>
                  <span class="stat-value">{{ space.total > 0 ? formatSize(space.total) : '无限制' }}</span>
                </div>
                <div class="stat-item">
                  <span class="stat-label">使用率</span>
                  <span class="stat-value">{{ space.total > 0 ? getUsagePercent(space.used, space.total) + '%' : '0%' }}</span>
                </div>
                <div class="stat-item">
                  <span class="stat-label">图片数量</span>
                  <span class="stat-value">{{ space.pictureCount || 0 }}</span>
                </div>
                <div class="stat-item">
                  <span class="stat-label">图片限制</span>
                  <span class="stat-value">{{ space.maxCount || '无限制' }}</span>
                </div>
                <div class="stat-item">
                  <span class="stat-label">空间类型</span>
                  <span class="stat-value">{{ getSpaceTypeName(space.type) }}</span>
                </div>
              </div>
              
              <div class="space-progress">
                <a-progress 
                  :percent="space.total > 0 ? getUsagePercent(space.used, space.total) : 0"
                  :status="space.total > 0 ? getProgressStatus(space.used, space.total) : 'normal'"
                  size="small"
                  :show-info="false"
                />
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧：VIP权益对比 -->
      <div class="vip-benefits-section glass">
        <div class="section-header">
          <h3 class="section-title">
            <CrownOutlined class="section-icon" />
            VIP权益对比
          </h3>
          <a-button 
            type="primary" 
            @click="showCareCodeModal = true"
            :icon="h(GiftOutlined)"
            class="upgrade-btn"
          >
            兑换卡密
          </a-button>
        </div>

        <!-- 会员权益对比表格 -->
        <div class="benefits-table">
          <a-table
            :columns="benefitColumns"
            :data-source="benefitData"
            :pagination="false"
            :bordered="true"
            size="middle"
            class="vip-benefits-table"
            :scroll="{ y: 'calc(100vh - 450px)' }"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'feature'">
                <span class="feature-name">{{ record.feature }}</span>
              </template>
              <template v-else-if="column.key === 'free'">
                <span v-if="record.free === true" class="check-icon">
                  <CheckOutlined style="color: #52c41a" />
                </span>
                <span v-else-if="record.free === false" class="close-icon">
                  <CloseOutlined style="color: #ff4d4f" />
                </span>
                <span v-else class="feature-text">{{ record.free }}</span>
              </template>
              <template v-else-if="column.key === 'vip'">
                <span v-if="record.vip === true" class="check-icon">
                  <CheckOutlined style="color: #52c41a" />
                </span>
                <span v-else-if="record.vip === false" class="close-icon">
                  <CloseOutlined style="color: #ff4d4f" />
                </span>
                <span v-else class="feature-text">{{ record.vip }}</span>
              </template>
              <template v-else-if="column.key === 'svip'">
                <span v-if="record.svip === true" class="check-icon">
                  <CheckOutlined style="color: #52c41a" />
                </span>
                <span v-else-if="record.svip === false" class="close-icon">
                  <CloseOutlined style="color: #ff4d4f" />
                </span>
                <span v-else class="feature-text">{{ record.svip }}</span>
              </template>
            </template>
          </a-table>
          
          <!-- 购买联系信息 -->
          <div class="contact-info-card">
            <div class="contact-header">
              <MailOutlined class="contact-icon" />
              <span class="contact-title">购买会员联系</span>
            </div>
            <div class="contact-email-display">703793464@qq.com</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 编辑用户信息弹窗 -->
    <a-modal
      v-model:open="showEditModal"
      title="编辑个人信息"
      @ok="handleUpdateProfile"
      @cancel="resetEditForm"
      :confirm-loading="updateLoading"
      width="600px"
    >
      <a-form :model="editForm" layout="vertical">
        <!-- 头像上传 -->
        <a-form-item label="头像">
          <div class="edit-avatar-section">
            <a-avatar 
              :size="80" 
              :src="editAvatarUrl" 
              class="edit-avatar-preview"
            >
              {{ editForm.userName?.charAt(0) }}
            </a-avatar>
            <div class="edit-avatar-controls">
              <a-upload
                v-model:file-list="editAvatarFileList"
                name="file"
                list-type="picture"
                :show-upload-list="false"
                :before-upload="beforeAvatarUpload"
                @change="handleEditAvatarChange"
                accept="image/*"
              >
                <a-button 
                  type="dashed" 
                  :icon="h(UploadOutlined)"
                  :loading="editAvatarLoading"
                  size="small"
                >
                  {{ editAvatarLoading ? '上传中...' : '选择头像' }}
                </a-button>
              </a-upload>
              <p class="upload-tip">支持jpg、png格式，文件大小不超过2MB</p>
            </div>
          </div>
        </a-form-item>
        
        <a-form-item label="用户名" name="userName" :rules="[{ required: true, message: '请输入用户名' }]">
          <a-input v-model:value="editForm.userName" placeholder="请输入用户名" />
        </a-form-item>
        
        <a-form-item label="个人简介" name="userProfile">
          <a-textarea 
            v-model:value="editForm.userProfile" 
            placeholder="请输入个人简介"
            :rows="4"
            :maxlength="200"
            show-count
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 更换头像弹窗 -->
    <a-modal
      v-model:open="showAvatarModal"
      title="更换头像"
      @ok="handleUpdateAvatar"
      @cancel="resetAvatarForm"
      :confirm-loading="avatarLoading"
      width="400px"
    >
      <div class="avatar-upload">
        <a-upload
          v-model:file-list="avatarFileList"
          name="file"
          list-type="picture-card"
          :show-upload-list="false"
          :before-upload="beforeAvatarUpload"
          @change="handleAvatarChange"
        >
          <div v-if="avatarUrl" class="avatar-preview">
            <img :src="avatarUrl" alt="avatar" />
          </div>
          <div v-else class="upload-area">
            <PlusOutlined />
            <div>上传头像</div>
          </div>
        </a-upload>
        <p class="upload-tip">
          支持jpg、png格式，文件大小不超过2MB
        </p>
      </div>
    </a-modal>

    <!-- 兑换卡密弹窗 -->
    <a-modal
      v-model:open="showCareCodeModal"
      title="兑换卡密"
      @ok="handleUseCareCode"
      @cancel="resetCareCodeForm"
      :confirm-loading="careCodeLoading"
      width="400px"
    >
      <a-form :model="careCodeForm" layout="vertical">
        <a-form-item 
          label="卡密" 
          name="careCode" 
          :rules="[{ required: true, message: '请输入卡密' }]"
        >
          <a-input 
            v-model:value="careCodeForm.careCode" 
            placeholder="请输入卡密"
            style="font-family: 'Courier New', monospace"
          />
        </a-form-item>
        
        <div class="care-code-tips">
          <h4>温馨提示：</h4>
          <ul>
            <li>请确保卡密输入正确</li>
            <li>每个卡密只能使用一次</li>
            <li>VIP权益立即生效</li>
            <li>如有问题请联系客服</li>
          </ul>
        </div>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, h } from 'vue'
import { message } from 'ant-design-vue'
import {
  UserOutlined,
  EditOutlined,
  CrownOutlined,
  GiftOutlined,
  CheckOutlined,
  CloseOutlined,
  PlusOutlined,
  MailOutlined,
  UploadOutlined,
  DatabaseOutlined
} from '@ant-design/icons-vue'
import { getUserInfoVoByIdUsingGet, updateSelfUsingPost } from '@/api/userController'
import { useCareCodeUsingPost } from '@/api/careCodeController'
import { useLoginUserStore } from '@/stores/useLoginUserStore'
import { uploadAvatarFileUsingPost } from '@/api/fileController'
import { getSpaceUsageAnalyzeUsingPost } from '@/api/spaceAnalyzeController'
import { listSpaceVoByPageUsingPost } from '@/api/spaceController'
import { SPACE_TYPE_ENUM } from '@/constants/space'

// 状态管理
const loginUserStore = useLoginUserStore()

// 响应式数据
const loading = ref(false)
const updateLoading = ref(false)
const avatarLoading = ref(false)
const careCodeLoading = ref(false)
const showEditModal = ref(false)
const showAvatarModal = ref(false)
const showCareCodeModal = ref(false)
const userInfo = ref<API.UserInfoVO | null>(null)
const avatarUrl = ref('')
const avatarFileList = ref<any[]>([])
const editAvatarUrl = ref('')
const editAvatarFileList = ref<any[]>([])
const editAvatarLoading = ref(false)

// 表单数据
const editForm = reactive({
  userName: '',
  userProfile: ''
})

const careCodeForm = reactive({
  careCode: ''
})

// 空间使用数据
const spaceUsage = ref<any[]>([])

// 会员权益对比表格配置
const benefitColumns = [
  {
    title: '功能特权',
    key: 'feature',
    dataIndex: 'feature',
    width: 160,
    ellipsis: false,
  },
  {
    title: '普通用户',
    key: 'free',
    dataIndex: 'free',
    align: 'center',
    width: 120,
  },
  {
    title: 'VIP会员',
    key: 'vip',
    dataIndex: 'vip',
    align: 'center',
    width: 120,
  },
  {
    title: 'SVIP会员',
    key: 'svip',
    dataIndex: 'svip',
    align: 'center',
    width: 120,
  },
]

const benefitData = [
  { key: '1', feature: '图片上传', free: true, vip: true, svip: true },
  { key: '2', feature: '公共空间访问', free: true, vip: true, svip: true },
  { key: '3', feature: '基础搜索功能', free: true, vip: true, svip: true },
  { key: '4', feature: '私有空间数量', free: false, vip: '3个', svip: '无限' },
  { key: '5', feature: '高级搜索功能', free: false, vip: true, svip: true },
  { key: '6', feature: '批量操作', free: false, vip: true, svip: true },
  { key: '7', feature: 'AI图片生成', free: false, vip: false, svip: true },
  { key: '8', feature: 'AI图片修复', free: false, vip: false, svip: true },
  { key: '9', feature: '专属客服支持', free: false, vip: true, svip: true },
  { key: '10', feature: '优先处理权限', free: false, vip: false, svip: true },
  { key: '11', feature: '数据导出功能', free: false, vip: false, svip: true },
  { key: '12', feature: '专业图片水印', free: false, vip: true, svip: true },
  { key: '13', feature: '云端同步备份', free: false, vip: true, svip: true },
  { key: '14', feature: '高清图片下载', free: false, vip: true, svip: true },
]

// 方法
const loadUserInfo = async () => {
  if (!loginUserStore.loginUser?.id) {
    message.error('用户未登录')
    return
  }
  
  loading.value = true
  try {
    const res = await getUserInfoVoByIdUsingGet({
      id: loginUserStore.loginUser.id
    })
    
    if (res.data.code === 0) {
      userInfo.value = res.data.data || null
      // 初始化编辑表单
      if (userInfo.value) {
        editForm.userName = userInfo.value.userName || ''
        editForm.userProfile = userInfo.value.userProfile || ''
        avatarUrl.value = userInfo.value.userAvatar || ''
        editAvatarUrl.value = userInfo.value.userAvatar || ''
      }
      
      // 加载空间使用情况
      await loadSpaceUsage()
    } else {
      message.error(res.data.message || '获取用户信息失败')
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    message.error('获取用户信息失败')
  } finally {
    loading.value = false
  }
}

const loadSpaceUsage = async () => {
  try {
    // 检查是否为管理员
    const isAdmin = loginUserStore.loginUser?.userRole === 'admin'
    
    if (isAdmin) {
      // 管理员查看公共空间使用情况
      const res = await getSpaceUsageAnalyzeUsingPost({
        queryPublic: true
      })
      
      if (res.data.code === 0 && res.data.data) {
        const data = res.data.data
        spaceUsage.value = [{
          id: 'public',
          name: '公共空间',
          type: 'public',
          used: data.usedSize || 0,
          total: data.maxSize || 0,
          pictureCount: data.usedCount || 0,
          maxCount: data.maxCount || 0
        }]
      } else {
        console.error('获取公共空间数据失败:', res.data.message || '未知错误')
        spaceUsage.value = []
      }
    } else {
      // 普通用户：先获取用户的空间列表，然后获取每个空间的使用情况
      if (!loginUserStore.loginUser?.id) {
        spaceUsage.value = []
        return
      }

      try {
        // 获取用户的私有空间列表
        const spaceListRes = await listSpaceVoByPageUsingPost({
          userId: loginUserStore.loginUser.id,
          current: 1,
          pageSize: 10, // 获取前10个空间
          spaceType: SPACE_TYPE_ENUM.PRIVATE,
        })
        
        if (spaceListRes.data.code === 0 && spaceListRes.data.data?.records && spaceListRes.data.data.records.length > 0) {
          const spaces = spaceListRes.data.data.records
          const spaceUsagePromises = spaces.map(async (space) => {
            try {
              // 为每个空间获取使用情况
              const usageRes = await getSpaceUsageAnalyzeUsingPost({
                spaceId: space.id?.toString()
              })
              
              if (usageRes.data.code === 0 && usageRes.data.data) {
                const data = usageRes.data.data
                return {
                  id: space.id,
                  name: space.spaceName || '未命名空间',
                  type: 'private',
                  used: data.usedSize || 0,
                  total: data.maxSize || 0,
                  pictureCount: data.usedCount || 0,
                  maxCount: data.maxCount || 0
                }
              }
              return null
            } catch (error) {
              console.error(`获取空间 ${space.id} 使用情况失败:`, error)
              return null
            }
          })
          
          const results = await Promise.all(spaceUsagePromises)
          spaceUsage.value = results.filter(result => result !== null)
        } else {
          // 用户没有私有空间
          spaceUsage.value = []
        }
      } catch (userError) {
        console.error('获取用户空间列表失败:', userError)
        spaceUsage.value = []
      }
    }
  } catch (error) {
    console.error('获取空间使用情况失败:', error)
    spaceUsage.value = []
  }
}

const handleUpdateProfile = async () => {
  updateLoading.value = true
  
  try {
    const res = await updateSelfUsingPost({
      userName: editForm.userName,
      userProfile: editForm.userProfile,
      userAvatar: editAvatarUrl.value
    })
    
    if (res.data.code === 0) {
      if (userInfo.value) {
        userInfo.value.userName = editForm.userName
        userInfo.value.userProfile = editForm.userProfile
        userInfo.value.userAvatar = editAvatarUrl.value
      }
      
      // 更新store中的用户信息
      if (loginUserStore.loginUser) {
        loginUserStore.loginUser.userName = editForm.userName
        loginUserStore.loginUser.userAvatar = editAvatarUrl.value
      }
      
      message.success('更新成功')
      showEditModal.value = false
    } else {
      message.error(res.data.message || '更新失败')
    }
  } catch (error) {
    console.error('更新失败:', error)
    message.error('更新失败')
  } finally {
    updateLoading.value = false
  }
}

const resetEditForm = () => {
  if (userInfo.value) {
    editForm.userName = userInfo.value.userName || ''
    editForm.userProfile = userInfo.value.userProfile || ''
    editAvatarUrl.value = userInfo.value.userAvatar || ''
  }
  editAvatarFileList.value = []
  editAvatarLoading.value = false
}

const handleEditAvatarChange = async (info: any) => {
  if (info.file.status === 'uploading') {
    editAvatarLoading.value = true
    return
  }
  
  try {
    // 使用uploadAvatarFileUsingPost上传头像文件
    const res = await uploadAvatarFileUsingPost(info.file.originFileObj)
    
    if ((res.data as any)?.code === 0 && (res.data as any)?.data) {
      editAvatarUrl.value = (res.data as any).data
      editAvatarLoading.value = false
      message.success('头像上传成功')
    } else {
      message.error('头像上传失败：' + ((res.data as any)?.message || '未知错误'))
      editAvatarLoading.value = false
    }
  } catch (error) {
    console.error('头像上传失败:', error)
    message.error('头像上传失败')
    editAvatarLoading.value = false
  }
}

const beforeAvatarUpload = (file: any) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
  if (!isJpgOrPng) {
    message.error('只能上传 JPG/PNG 格式的图片!')
    return false
  }
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    message.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

const handleAvatarChange = async (info: any) => {
  if (info.file.status === 'uploading') {
    avatarLoading.value = true
    return
  }
  
  try {
    // 使用uploadAvatarFileUsingPost上传头像文件
    const res = await uploadAvatarFileUsingPost(info.file.originFileObj)
    
    if ((res.data as any)?.code === 0 && (res.data as any)?.data) {
      avatarUrl.value = (res.data as any).data
      avatarLoading.value = false
    } else {
      message.error('图片上传失败：' + ((res.data as any)?.message || '未知错误'))
      avatarLoading.value = false
    }
  } catch (error) {
    console.error('图片上传失败:', error)
    message.error('图片上传失败')
    avatarLoading.value = false
  }
}

const handleUpdateAvatar = async () => {
  if (!avatarUrl.value) {
    message.error('请选择头像')
    return
  }
  
  avatarLoading.value = true
  
  try {
    const res = await updateSelfUsingPost({
      userAvatar: avatarUrl.value
    })
    
    if (res.data.code === 0) {
      if (userInfo.value) {
        userInfo.value.userAvatar = avatarUrl.value
      }
      
      // 更新store中的用户头像
      if (loginUserStore.loginUser) {
        loginUserStore.loginUser.userAvatar = avatarUrl.value
      }
      
      message.success('头像更新成功')
      showAvatarModal.value = false
    } else {
      message.error(res.data.message || '头像更新失败')
    }
  } catch (error) {
    console.error('头像更新失败:', error)
    message.error('头像更新失败')
  } finally {
    avatarLoading.value = false
  }
}

const resetAvatarForm = () => {
  avatarUrl.value = userInfo.value?.userAvatar || ''
  avatarFileList.value = []
}

const handleUseCareCode = async () => {
  if (!careCodeForm.careCode) {
    message.error('请输入卡密')
    return
  }
  
  if (!loginUserStore.loginUser?.userAccount) {
    message.error('用户未登录')
    return
  }
  
  careCodeLoading.value = true
  try {
    const res = await useCareCodeUsingPost({
      careCode: careCodeForm.careCode,
      userAccount: loginUserStore.loginUser.userAccount
    })
    
    if (res.data.code === 0) {
      message.success('卡密兑换成功')
      showCareCodeModal.value = false
      resetCareCodeForm()
      // 重新加载用户信息
      loadUserInfo()
    } else {
      message.error(res.data.message || '卡密兑换失败')
    }
  } catch (error) {
    console.error('卡密兑换失败:', error)
    message.error('卡密兑换失败')
  } finally {
    careCodeLoading.value = false
  }
}

const resetCareCodeForm = () => {
  careCodeForm.careCode = ''
}

// 工具方法
const getVipAvatarClass = () => {
  if (!userInfo.value?.vipLevel || userInfo.value.vipLevel === 0) return ''
  return userInfo.value.vipLevel === 1 ? 'vip-avatar' : 'svip-avatar'
}

const getVipBadgeClass = () => {
  if (!userInfo.value?.vipLevel || userInfo.value.vipLevel === 0) return ''
  return userInfo.value.vipLevel === 1 ? 'vip-badge-content' : 'svip-badge-content'
}

const isVipExpiringSoon = () => {
  if (!userInfo.value?.expireTime || isVipForever()) return false
  const expireTime = new Date(userInfo.value.expireTime)
  const now = new Date()
  const diffDays = Math.ceil((expireTime.getTime() - now.getTime()) / (1000 * 60 * 60 * 24))
  return diffDays <= 7 && diffDays > 0
}

const isVipForever = () => {
  if (!userInfo.value?.expireTime) return false
  const expireTime = new Date(userInfo.value.expireTime)
  const now = new Date()
  // 如果到期时间超过80年，认为是永久会员
  const diffYears = (expireTime.getTime() - now.getTime()) / (1000 * 60 * 60 * 24 * 365)
  return diffYears > 80
}

const getSpaceTypeName = (type: string) => {
  return type === 'private' ? '私有空间' : '公共空间'
}

const getUsagePercent = (used: number, total: number) => {
  return Math.round((used / total) * 100)
}

const getProgressStatus = (used: number, total: number) => {
  const percent = (used / total) * 100
  if (percent >= 90) return 'exception'
  if (percent >= 70) return 'active'
  return 'normal'
}

const formatSize = (bytes: number) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

const formatDate = (dateStr?: string) => {
  if (!dateStr) return '-'
  return new Date(dateStr).toLocaleString('zh-CN')
}

// 生命周期
onMounted(() => {
  loadUserInfo()
})
</script>

<style scoped>
.personal-center-page {
  padding: 24px;
  min-height: 100vh;
  background: linear-gradient(135deg, 
    var(--primary-gradient-start) 0%, 
    var(--primary-gradient-end) 100%);
}

/* 深色模式适配 */
.dark .personal-center-page {
  background: linear-gradient(135deg, 
    var(--dark-bg-primary) 0%, 
    var(--dark-bg-secondary) 100%);
}

.page-header {
  margin-bottom: 24px;
  text-align: center;
}

.page-title {
  font-size: 32px;
  font-weight: 700;
  margin-bottom: 8px;
}

.page-subtitle {
  font-size: 16px;
  opacity: 0.8;
  margin: 0;
}

.gradient-text {
  background: linear-gradient(45deg, #6366f1, #8b5cf6, #ec4899);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.content-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 24px;
  align-items: start;
}

.user-info-section,
.vip-benefits-section {
  display: flex;
  flex-direction: column;
  height: 100%;
  min-height: 600px;
}

.glass {
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(20px);
  border: 1px solid rgba(0, 0, 0, 0.1);
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  padding: 24px;
  color: #333;
}

.dark .glass {
  background: rgba(30, 30, 30, 0.9);
  border: 1px solid rgba(255, 255, 255, 0.1);
  color: rgba(255, 255, 255, 0.9);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 20px;
  font-weight: 600;
  margin: 0;
}

.section-icon {
  font-size: 24px;
  color: #6366f1;
}

.avatar-section {
  text-align: center;
  margin-bottom: 24px;
}

.avatar-container {
  position: relative;
  display: inline-block;
  margin-bottom: 12px;
}

.avatar-container:hover .change-avatar-overlay {
  opacity: 1;
  visibility: visible;
}

.user-avatar {
  border: 3px solid rgba(255, 255, 255, 0.2);
  transition: all 0.3s ease;
}

.vip-avatar .user-avatar {
  border: 3px solid #ffd700;
  box-shadow: 0 0 20px rgba(255, 215, 0, 0.3);
}

.svip-avatar .user-avatar {
  border: 3px solid #8b5cf6;
  box-shadow: 0 0 20px rgba(139, 92, 246, 0.3);
}

.vip-badge {
  position: absolute;
  top: -5px;
  right: -5px;
}

.vip-badge-content,
.svip-badge-content {
  padding: 2px 6px;
  border-radius: 8px;
  font-size: 10px;
  font-weight: 700;
  color: white;
}

.vip-badge-content {
  background: linear-gradient(45deg, #ffd700, #ffed4e);
  color: #000;
}

.svip-badge-content {
  background: linear-gradient(45deg, #8b5cf6, #ec4899);
}

.change-avatar-overlay {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  opacity: 0;
  visibility: hidden;
  transition: all 0.3s ease;
  background: rgba(0, 0, 0, 0.7) !important;
  color: white !important;
  border: none !important;
  border-radius: 50px;
  font-size: 12px;
  height: 32px;
  padding: 0 12px;
  backdrop-filter: blur(10px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
}

.change-avatar-overlay:hover {
  background: rgba(0, 0, 0, 0.8) !important;
  transform: translate(-50%, -50%) scale(1.05);
}

.picture-count {
  font-size: 12px;
  color: #6366f1;
  background: rgba(99, 102, 241, 0.1);
  padding: 2px 8px;
  border-radius: 12px;
  margin-left: 8px;
}

.user-details {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.info-item {
  display: flex;
  align-items: flex-start;
  gap: 8px;
}

.info-label {
  font-weight: 600;
  opacity: 0.8;
  min-width: 80px;
}

.info-value {
  flex: 1;
}

.info-value.empty {
  opacity: 0.6;
  font-style: italic;
}

.expire-warning {
  color: #ff4d4f !important;
  font-weight: 600;
}

.profile-item {
  align-items: flex-start;
}

.profile-content {
  flex: 1;
}

.profile-text {
  margin: 0;
  line-height: 1.6;
  word-break: break-word;
}

.user-profile-main {
  flex: 1;
}

.space-usage-section {
  margin-top: auto;
  padding-top: 24px;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
}

.usage-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 16px;
}

.space-cards {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.space-card {
  background: rgba(255, 255, 255, 0.5);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 12px;
  padding: 16px;
  transition: all 0.3s ease;
}

.space-card:hover {
  background: rgba(255, 255, 255, 0.7);
  border-color: rgba(99, 102, 241, 0.3);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.dark .space-card {
  background: rgba(30, 30, 30, 0.6);
  border-color: rgba(255, 255, 255, 0.1);
}

.dark .space-card:hover {
  background: rgba(30, 30, 30, 0.8);
  border-color: rgba(139, 92, 246, 0.3);
}

.space-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.space-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.space-name {
  font-weight: 600;
  font-size: 14px;
}

.space-type {
  font-size: 12px;
  opacity: 0.7;
}

.space-stats {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  grid-template-rows: 1fr 1fr;
  gap: 12px;
  margin-bottom: 12px;
}

.stat-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
  text-align: center;
}

.stat-label {
  font-size: 12px;
  opacity: 0.7;
}

.stat-value {
  font-size: 14px;
  font-weight: 600;
  color: #6366f1;
}

.space-progress {
  margin-top: 8px;
}

.benefits-table {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.vip-benefits-table {
  flex: 1;
  margin-bottom: 16px;
}

.vip-benefits-table :deep(.ant-table) {
  background: transparent;
}

.vip-benefits-table :deep(.ant-table-thead > tr > th) {
  background: rgba(0, 0, 0, 0.05);
  border-color: rgba(0, 0, 0, 0.1);
  color: #333;
  font-weight: 600;
  text-align: center;
}

.vip-benefits-table :deep(.ant-table-tbody > tr > td) {
  background: rgba(255, 255, 255, 0.7);
  border-color: rgba(0, 0, 0, 0.05);
  color: #333;
  padding: 12px 16px;
}

.vip-benefits-table :deep(.ant-table-tbody > tr:hover > td) {
  background: rgba(99, 102, 241, 0.1);
}

.dark .vip-benefits-table :deep(.ant-table-thead > tr > th) {
  background: rgba(30, 30, 30, 0.8);
  border-color: rgba(255, 255, 255, 0.2);
  color: rgba(255, 255, 255, 0.9);
}

.dark .vip-benefits-table :deep(.ant-table-tbody > tr > td) {
  background: rgba(30, 30, 30, 0.6);
  border-color: rgba(255, 255, 255, 0.1);
  color: rgba(255, 255, 255, 0.9);
}

.dark .vip-benefits-table :deep(.ant-table-tbody > tr:hover > td) {
  background: rgba(30, 30, 30, 0.9);
}

.feature-name {
  font-weight: 500;
}

.check-icon, .close-icon {
  display: flex;
  justify-content: center;
  align-items: center;
}

.feature-text {
  font-weight: 500;
  color: #6366f1;
}

.contact-feature {
  font-weight: 600;
  color: #6366f1;
  background: linear-gradient(45deg, #6366f1, #8b5cf6);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.contact-info-card {
  margin-top: 16px;
  padding: 16px;
  background: linear-gradient(135deg, 
    rgba(99, 102, 241, 0.1) 0%, 
    rgba(139, 92, 246, 0.08) 100%);
  border: 1px solid rgba(99, 102, 241, 0.2);
  border-radius: 12px;
  transition: all 0.3s ease;
}

.contact-info-card:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(99, 102, 241, 0.15);
  border-color: rgba(99, 102, 241, 0.3);
}

.contact-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.contact-icon {
  font-size: 18px;
  color: #6366f1;
}

.contact-title {
  font-size: 14px;
  font-weight: 600;
  color: #6366f1;
}

.contact-email-display {
  font-size: 16px;
  font-weight: 700;
  color: #6366f1;
  font-family: 'Courier New', monospace;
  background: rgba(255, 255, 255, 0.6);
  padding: 8px 12px;
  border-radius: 6px;
  border: 1px solid rgba(99, 102, 241, 0.2);
  text-align: center;
  letter-spacing: 0.5px;
}

.dark .contact-email-display {
  background: rgba(30, 30, 30, 0.8);
  color: #8b5cf6;
  border-color: rgba(139, 92, 246, 0.3);
}


.upgrade-btn {
  background: linear-gradient(45deg, #6366f1, #8b5cf6);
  border: none;
  border-radius: 8px;
  height: 36px;
  font-weight: 600;
}

.avatar-upload {
  text-align: center;
}

.avatar-preview img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 8px;
}

.upload-area {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 120px;
  border: 2px dashed rgba(255, 255, 255, 0.3);
  border-radius: 8px;
  cursor: pointer;
}

.upload-tip {
  margin-top: 12px;
  font-size: 12px;
  opacity: 0.7;
}

.care-code-tips {
  margin-top: 16px;
  padding: 16px;
  background: rgba(99, 102, 241, 0.1);
  border-radius: 8px;
}

.care-code-tips h4 {
  margin-bottom: 8px;
  font-size: 14px;
  font-weight: 600;
}

.care-code-tips ul {
  margin: 0;
  padding-left: 16px;
}

.care-code-tips li {
  font-size: 12px;
  opacity: 0.8;
  margin-bottom: 4px;
}

.edit-avatar-section {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 16px;
  background: rgba(99, 102, 241, 0.05);
  border: 1px dashed rgba(99, 102, 241, 0.2);
  border-radius: 8px;
}

.edit-avatar-preview {
  border: 2px solid rgba(99, 102, 241, 0.3);
  transition: all 0.3s ease;
}

.edit-avatar-controls {
  flex: 1;
}

.edit-avatar-controls .upload-tip {
  margin-top: 8px;
  margin-bottom: 0;
  font-size: 12px;
  opacity: 0.7;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .content-grid {
    grid-template-columns: 1fr;
    gap: 16px;
  }
  
  .benefits-comparison {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .personal-center-page {
    padding: 16px;
  }
  
  .page-title {
    font-size: 24px;
  }
  
  .glass {
    padding: 16px;
  }
  
  .section-header {
    flex-direction: column;
    gap: 12px;
  }
  
  .info-item {
    flex-direction: column;
    gap: 4px;
  }
  
  .info-label {
    min-width: auto;
  }
}
</style>
